package com.example.javapoint.threads.deadLock;

public class DeadlockSolved2 {
    private final String resource1 = "alibaba";
    private final String resource2 = "tencent";

    public static void main(String args[]) {
        DeadlockSolved2 test = new DeadlockSolved2();
        String a = test.resource1;
        String b = test.resource2;
        // Thread-1
        Runnable b1 = () -> {
            synchronized (b) {
                try {
                    /* Adding delay so that both threads can start trying to lock resources */
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                // Thread-1 have resource1 but need resource2 also
                synchronized (a) {
                    System.out.println(a + " In block 1");
                }
            }
        };

        // Thread-2
        Runnable b2 = () -> {
            synchronized (b) {
                // Thread-2 have resource2 but need resource1 also
                synchronized (a) {
                    System.out.println( b + " In block 2");
                }
            }
        };


        new Thread(b1).start();
        new Thread(b2).start();
    }
}